// 场景设置
let scene, camera, renderer, controls;
let producers = [], consumers = [], decomposers = [];
let raycaster, mouse;

// 初始化场景
function init() {
    // 创建场景
    scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87CEEB);
    scene.fog = new THREE.Fog(0x87CEEB, 10, 100);

    // 创建相机
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.set(0, 15, 30);

    // 创建渲染器
    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;
    document.getElementById('container').appendChild(renderer.domElement);

    // 添加控制器
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    controls.enableDamping = true;
    controls.dampingFactor = 0.05;
    controls.maxPolarAngle = Math.PI / 2;

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    scene.add(ambientLight);

    const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
    directionalLight.position.set(10, 20, 5);
    directionalLight.castShadow = true;
    directionalLight.shadow.mapSize.width = 2048;
    directionalLight.shadow.mapSize.height = 2048;
    scene.add(directionalLight);

    // 创建地面（湿地）
    createWetland();

    // 创建生态系统元素
    createProducers();
    createConsumers();
    createDecomposers();

    // 初始化射线检测
    raycaster = new THREE.Raycaster();
    mouse = new THREE.Vector2();

    // 添加事件监听
    window.addEventListener('resize', onWindowResize);
    renderer.domElement.addEventListener('click', onMouseClick);

    // 添加鼠标悬停效果
    renderer.domElement.addEventListener('mousemove', onMouseMove);

    animate();
}

// 创建湿地地面
function createWetland() {
    const groundGeometry = new THREE.PlaneGeometry(50, 50);
    const groundMaterial = new THREE.MeshLambertMaterial({ color: 0x2E8B57 });
    const ground = new THREE.Mesh(groundGeometry, groundMaterial);
    ground.rotation.x = -Math.PI / 2;
    ground.receiveShadow = true;
    scene.add(ground);

    // 添加水面
    const waterGeometry = new THREE.PlaneGeometry(50, 50);
    const waterMaterial = new THREE.MeshPhongMaterial({ 
        color: 0x006994, 
        transparent: true, 
        opacity: 0.7 
    });
    const water = new THREE.Mesh(waterGeometry, waterMaterial);
    water.rotation.x = -Math.PI / 2;
    water.position.y = 0.1;
    scene.add(water);
}

// 创建生产者（水草）
function createProducers() {
    const positions = [
        { x: -10, z: -8 }, { x: -8, z: -5 }, { x: -12, z: -3 },
        { x: 8, z: -10 }, { x: 10, z: -7 }, { x: 12, z: -4 },
        { x: -5, z: 8 }, { x: -3, z: 10 }, { x: -7, z: 12 }
    ];

    positions.forEach(pos => {
        const group = new THREE.Group();
        
        // 创建水草
        for (let i = 0; i < 5; i++) {
            const stemGeometry = new THREE.CylinderGeometry(0.1, 0.2, 2 + Math.random() * 2, 8);
            const stemMaterial = new THREE.MeshLambertMaterial({ color: 0x228B22 });
            const stem = new THREE.Mesh(stemGeometry, stemMaterial);
            
            stem.position.set(
                (Math.random() - 0.5) * 2,
                stemGeometry.parameters.height / 2,
                (Math.random() - 0.5) * 2
            );
            stem.castShadow = true;
            group.add(stem);
        }

        group.position.set(pos.x, 0, pos.z);
        group.userData = { type: 'producer', name: '水草' };
        scene.add(group);
        producers.push(group);
    });
}

// 创建消费者（鱼、虾、白鹭）
function createConsumers() {
    // 创建鱼群
    for (let i = 0; i < 8; i++) {
        const fishGeometry = new THREE.ConeGeometry(0.5, 2, 8);
        const fishMaterial = new THREE.MeshLambertMaterial({ color: 0xFF6347 });
        const fish = new THREE.Mesh(fishGeometry, fishMaterial);
        
        fish.position.set(
            (Math.random() - 0.5) * 20,
            1 + Math.random() * 2,
            (Math.random() - 0.5) * 20
        );
        fish.rotation.z = Math.PI / 2;
        fish.castShadow = true;
        fish.userData = { type: 'consumer', name: '鱼', subtype: 'fish' };
        scene.add(fish);
        consumers.push(fish);
    }

    // 创建虾群
    for (let i = 0; i < 12; i++) {
        const shrimpGeometry = new THREE.BoxGeometry(0.8, 0.3, 0.5);
        const shrimpMaterial = new THREE.MeshLambertMaterial({ color: 0xFF4500 });
        const shrimp = new THREE.Mesh(shrimpGeometry, shrimpMaterial);
        
        shrimp.position.set(
            (Math.random() - 0.5) * 25,
            0.5 + Math.random() * 1,
            (Math.random() - 0.5) * 25
        );
        shrimp.castShadow = true;
        shrimp.userData = { type: 'consumer', name: '虾', subtype: 'shrimp' };
        scene.add(shrimp);
        consumers.push(shrimp);
    }

    // 创建白鹭
    const egretGeometry = new THREE.ConeGeometry(0.3, 3, 8);
    const egretMaterial = new THREE.MeshLambertMaterial({ color: 0xFFFFFF });
    const egret = new THREE.Mesh(egretGeometry, egretMaterial);
    
    egret.position.set(5, 8, 5);
    egret.castShadow = true;
    egret.userData = { type: 'consumer', name: '白鹭', subtype: 'egret' };
    scene.add(egret);
    consumers.push(egret);
}

// 创建分解者（细菌真菌）
function createDecomposers() {
    const positions = [
        { x: -15, z: -15 }, { x: 15, z: -15 }, { x: -15, z: 15 }, { x: 15, z: 15 }
    ];

    positions.forEach(pos => {
        const group = new THREE.Group();
        
        // 创建分解者群体（用小球表示）
        for (let i = 0; i < 20; i++) {
            const microbeGeometry = new THREE.SphereGeometry(0.1 + Math.random() * 0.1, 8, 8);
            const microbeMaterial = new THREE.MeshLambertMaterial({ 
                color: new THREE.Color().setHSL(0.7 + Math.random() * 0.1, 0.8, 0.5) 
            });
            const microbe = new THREE.Mesh(microbeGeometry, microbeMaterial);
            
            microbe.position.set(
                (Math.random() - 0.5) * 5,
                0.1 + Math.random() * 0.5,
                (Math.random() - 0.5) * 5
            );
            group.add(microbe);
        }

        group.position.set(pos.x, 0, pos.z);
        group.userData = { type: 'decomposer', name: '细菌真菌' };
        scene.add(group);
        decomposers.push(group);
    });
}

// 鼠标点击事件
function onMouseClick(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);
    
    const allObjects = [...producers, ...consumers, ...decomposers];
    const intersects = raycaster.intersectObjects(allObjects, true);

    if (intersects.length > 0) {
        const object = intersects[0].object;
        let targetObject = object;
        
        // 查找父对象的userData
        while (targetObject && !targetObject.userData.type) {
            targetObject = targetObject.parent;
        }
        
        if (targetObject && targetObject.userData.type) {
            handleObjectClick(targetObject);
        }
    }
}

// 处理对象点击
function handleObjectClick(object) {
    const type = object.userData.type;
    
    switch(type) {
        case 'producer':
            showInfoPanel('生产者（水草）', 
                '通过光合作用制造有机物，为其他生物提供能量。作为生态系统的基础，水草将太阳能转化为化学能，是整个食物链的起点。');
            break;
            
        case 'consumer':
            if (object.userData.subtype === 'egret') {
                showFoodChainAnimation();
            } else {
                showInfoPanel('消费者（' + object.userData.name + '）', 
                    '作为食物链中的重要环节，' + object.userData.name + '通过捕食其他生物获取能量，维持生态系统的平衡。');
            }
            break;
            
        case 'decomposer':
            showInfoPanel('分解者（细菌真菌）', 
                '分解动植物遗体，将有机物转化为无机物（如二氧化碳、无机盐），回归土壤和大气供生产者重新利用，完成物质循环。');
            break;
    }
}

// 显示信息面板
function showInfoPanel(title, description) {
    document.getElementById('info-title').textContent = title;
    document.getElementById('info-description').textContent = description;
    document.getElementById('info-panel').classList.remove('hidden');
}

// 显示食物链动画
function showFoodChainAnimation() {
    document.getElementById('food-chain-panel').classList.remove('hidden');
    
    // 动画序列
    const items = ['plant', 'shrimp', 'fish', 'egret'];
    items.forEach((item, index) => {
        setTimeout(() => {
            const element = document.getElementById(item);
            element.classList.add('active');
            setTimeout(() => {
                element.classList.remove('active');
            }, 1000);
        }, index * 1500);
    });
}

// 鼠标悬停效果
function onMouseMove(event) {
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);
    
    const allObjects = [...producers, ...consumers, ...decomposers];
    const intersects = raycaster.intersectObjects(allObjects, true);

    // 重置所有对象的颜色
    allObjects.forEach(obj => {
        if (obj.material) {
            obj.material.emissive = new THREE.Color(0x000000);
        }
    });

    if (intersects.length > 0) {
        document.body.style.cursor = 'pointer';
    } else {
        document.body.style.cursor = 'default';
    }
}

// 窗口大小调整
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

// 动画循环
function animate() {
    requestAnimationFrame(animate);
    
    // 更新控制器
    controls.update();
    
    // 添加一些动态效果
    consumers.forEach(consumer => {
        if (consumer.userData.subtype === 'fish' || consumer.userData.subtype === 'shrimp') {
            consumer.position.x += Math.sin(Date.now() * 0.001 + consumer.position.z) * 0.01;
            consumer.position.z += Math.cos(Date.now() * 0.001 + consumer.position.x) * 0.01;
        }
    });
    
    renderer.render(scene, camera);
}

// 关闭按钮事件
document.getElementById('close-info').addEventListener('click', () => {
    document.getElementById('info-panel').classList.add('hidden');
});

document.getElementById('close-food-chain').addEventListener('click', () => {
    document.getElementById('food-chain-panel').classList.add('hidden');
});

// 初始化应用
init();